package gr.handmademarket.ui.pages;

import gr.handmademarket.ui.WebHandMadeSession;
import gr.handmademarket.ui.panels.AddressPanel;
import gr.handmademarket.util.PaymentUtils;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.UrlResourceReference;

import urn.ebay.apis.eBLBaseComponents.AddressType;

public class CheckoutPage 
extends CommonTemplatePage{

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	private static final String PAYPAL_GIF_URL = "https://www.paypal.com/en_US/i/logo/PayPal_mark_37x23.gif";
	
	private String token;
	
	private String payerId;
	
	public CheckoutPage(PageParameters params) {
		super();
		WebHandMadeSession session = (WebHandMadeSession) WebHandMadeSession.get();
		add(new Label("amount", session.getTotalAmount()));
		token = params.get("token").toString();
		payerId = params.get("PayerID").toString();
		PaymentUtils utils = new PaymentUtils();
		AddressType shippingAddress = utils.callGetExpressCheckout(token).getAddress();
		add(getAddressPanel("shippingAddressPanel", shippingAddress, "Shipping Address"));
		add(createPaymentLink());
	}
	
	private Panel getAddressPanel(String wicketId, AddressType address, String title){
		if (address != null){
			return new AddressPanel(wicketId, new CompoundPropertyModel<AddressType>(address), title);
		}
		return new EmptyPanel(wicketId);
	}
	
	/**
	 * @return ajax basket link.
	 */
	@SuppressWarnings("nls")
	private AjaxLink<Image> createPaymentLink(){
		UrlResourceReference imageReference = 
				new UrlResourceReference(Url.parse(PAYPAL_GIF_URL));
		
		Image image = new Image("confirmImg", imageReference);
		AjaxLink<Image> ajaxLink = new AjaxLink<Image>("confirmLink", new Model<Image>(image)) {
			/**
			 * serialVersionUID
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				PaymentUtils utils = new PaymentUtils();
				String billingId = utils.completePayment(token, 100d, payerId);
				System.out.println("billing id: "+billingId);
				setResponsePage(new HomePage());
			}
		};
		ajaxLink.add(image);
		return ajaxLink;
	}

}
